<?php

namespace app\api\service\douyin;

use app\api\model\douyin\DouyinEvent;
use app\api\model\douyin\DouyinStore;
use app\api\service\token\LoginToken;
use app\lib\douyin\douyin;
use app\lib\exception\douyin\DouyinException;
use think\Db;
use think\Exception;

class EventService
{
    private static $instance;

    public static function getInstance():EventService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * @param $attrs
     * @throws DouyinException
     */
    public function store($attrs){
        $i = 0;
        if(!empty($attrs)) {
            if (!is_array($attrs)) {
                $attrs = \GuzzleHttp\json_decode($attrs, true);
            }
            // 启动事务
            Db::startTrans();
            try {
                foreach ($attrs as $attr) {
                    $store = DouyinStore::where("aweme_id",$attr['aweme_id'])->findOrEmpty();
                    if ($store->isEmpty()){
                        DouyinStore::create([
                            "aweme_id"=>$attr['aweme_id'],
                            "likes"=>$attr['likes'],
                            "aweme_time"=>$attr['aweme_time']??null,
                            "topic"=>$attr['topic']??null,
                            "platform"=>$attr['platform'],
                            "get_time"=>date("Y-m-d H:i:s", time() - 600),
                            "status"=>1
                        ]);
                        $i ++;
                    }
                }
                // 提交事务
                Db::commit();
            } catch (Exception $e){
                var_dump($e->getMessage());
                // 回滚事务
                Db::rollback();
                throw new DouyinException([
                    'msg' => '采集失败',
                    'error_code' => 20001
                ]);
            }
        }

        return $i;
    }

    /**
     * @param $params
     * @throws DouyinException
     */
    public function randomStore($params){
        $data = "";
        $get_time = date("Y-m-d H:i:s", time() - 600);
        Db::startTrans();
        try {
            $data = DouyinStore::where("status",1)->where("get_time",'<',$get_time)->lock(true)->orderRand()->find();
            if ($data){
                DouyinStore::where("id",$data['id'])->update(
                    [
                        'get_time'=>date("Y-m-d H:i:s")
                    ]);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new DouyinException([
                'msg' => "图片无法分配",
                'error_code' => 20001
            ]);
        }
        return $data;
    }


    /**
     * @param $params
     * @throws DouyinException
     */
    public function addEvent($params){
        $uid = LoginToken::getInstance()->getCurrentUid()??"";
        Db::startTrans();
        try {
            DouyinEvent::create([
                'uid'=>$uid,
                'app_id'=>$params['app_id'],
                'imgs'=>$params['imgs']??[],
                'title'=>$params['title'],
                'type'=>1,
                'status'=>1
            ]);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new DouyinException([
                'msg' => "创建失败",
                'error_code' => 20001
            ]);
        }
        return true;
    }

    /**
     * @param $params
     * @throws DouyinException
     */
    public function getEvent($params){
        $pageSize = $params['pageSize']??50;
        $uid = LoginToken::getInstance()->getCurrentUid()??"";
        $event = DouyinEvent::field("id,title,imges,status,create_time,app_id,uid");
        if ($uid !=1){
            $event->where("uid",$uid);
        }

        if (!empty($params['status'])){
            if ($params['status'] != ""){
                $event->where($params);
            }
        }

        $list = $event->order("id desc")->paginate($pageSize);
        return $list;
    }

    /**
     * @param $params
     * @throws DouyinException
     */
    public function share($params){
        $info = DouyinEvent::where("id",$params['id'])->findOrEmpty();
        if ($info->isEmpty()){
            throw new DouyinException([
                'msg' => "任务不存在",
                'error_code' => 20001
            ]);
        }

        $douyin = new douyin();
        $data = [];
        $Not_necessary = [
            "title"=>$info->title,
            "image_list_path"=>$info['imgs'],

        ];
        #分享抖音号
        $ticket = $douyin->ticket();
        $attributes = [
            "nonce_str"=>$douyin->generateRandomString(),
            "ticket"=>$ticket,
            "timestamp"=>(string)time()
        ];
        $sign = $douyin->createSign($attributes);
        $attributes["signature"] = $sign;
        $Not_necessary['state'] = "";
        $baseUrl = $douyin->publishingContent($attributes,$Not_necessary);
        $data['baseUrl'] = $baseUrl;
        $uid = LoginToken::getInstance()->getCurrentUid()??"";
//        $log_data = [
//            "share_id"=>$Not_necessary['state'],
//            'list_id'=>$info['id'],
//            'uid'=>$uid
//        ];
        DB::startTrans();
        try {
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $data;
    }

    /**
     * @param $params
     * @throws DouyinException
     */
    public function backfillUrl($params){
        $info = DouyinEvent::where("id",$params['id'])->where("status",1)->findOrEmpty();
        if ($info->isEmpty()){
            throw new DouyinException([
                'msg' => "任务不存在",
                'error_code' => 20001
            ]);
        }
        $rs_1 = substr($params['url'],strpos($params['url'],"https"));
        $rs_2 = substr($rs_1,0,strpos($rs_1," "));
        DB::startTrans();
        try {
            $info->save(['status'=>3,'backfill_url'=>$rs_2]);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return true;
    }
}
